import json
from time import sleep

import execjs
import sys

from config_setting.config_setting import session


class Google():
    def __init__(self):
        # self.proxies = self.get_proxies()
        self.proxies = ''
        self.headers = self.get_headers()

    def get_headers(self):
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0',
                   'Accept-Encoding': 'gzip, deflate',
                   'Accept': '*/*',
                   'Connection': 'keep-alive'}
        return headers

    def set_proxies(self):
        url = 'http://d.jghttp.golangapi.com/getip?num=1&type=1&pro=&city=0&yys=0&port=1&time=3&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions='
        response = session.get(url)
        pro = response.text.strip()
        ip = pro.split(':')[0]
        port = pro.split(':')[1]
        proxies = {
            "http": "http://{}:{}".format(ip, port),
            "https": "https://{}:{}".format(ip, port),
        }
        return proxies

    def get_tk(self,text):
        ctx = execjs.compile("""
            function TL(a) {
            var k = "";
            var b = 406644;
            var b1 = 3293161072;
            var jd = ".";
            var $b = "+-a^+6";
            var Zb = "+-3^+b+-f";
            for (var e = [], f = 0, g = 0; g < a.length; g++) {
                var m = a.charCodeAt(g);
                128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023),
                e[f++] = m >> 18 | 240,
                e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
                e[f++] = m >> 6 & 63 | 128),
                e[f++] = m & 63 | 128)
            }
            a = b;
            for (f = 0; f < e.length; f++) a += e[f],
            a = RL(a, $b);
            a = RL(a, Zb);
            a ^= b1 || 0;
            0 > a && (a = (a & 2147483647) + 2147483648);
            a %= 1E6;
            return a.toString() + jd + (a ^ b)
          };
          function RL(a, b) {
            var t = "a";
            var Yb = "+";
            for (var c = 0; c < b.length - 2; c += 3) {
                var d = b.charAt(c + 2),
                d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
                d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
                a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
            }
            return a
          }
         """)
        return ctx.call("TL", text)

    def c2e_url(self,text):
        baseUrl = 'https://translate.google.cn/translate_a/single?client=webapp'
        baseUrl += '&sl=zh-CN'
        baseUrl += '&tl=en'
        baseUrl += '&hl=zh-CN'
        baseUrl += '&dt=at'
        baseUrl += '&dt=bd'
        baseUrl += '&dt=ex'
        baseUrl += '&dt=ld'
        baseUrl += '&dt=md'
        baseUrl += '&dt=qca'
        baseUrl += '&dt=rw'
        baseUrl += '&dt=rm'
        baseUrl += '&dt=ss'
        baseUrl += '&dt=t'
        baseUrl += '&otf=1'
        baseUrl += '&ssel=3'
        baseUrl += '&tsel=3'
        baseUrl += '&kc=4'
        baseUrl += '&tk='+ self.get_tk(text)
        baseUrl += '&q='+text
        return baseUrl

    def e2c_url(self,text):
        baseUrl = 'https://translate.google.cn/translate_a/single?client=webapp'
        baseUrl += '&sl=en'
        baseUrl += '&tl=zh-CN'
        baseUrl += '&hl=zh-CN'
        baseUrl += '&dt=at'
        baseUrl += '&dt=bd'
        baseUrl += '&dt=ex'
        baseUrl += '&dt=ld'
        baseUrl += '&dt=md'
        baseUrl += '&dt=qca'
        baseUrl += '&dt=rw'
        baseUrl += '&dt=rm'
        baseUrl += '&dt=ss'
        baseUrl += '&dt=t'
        baseUrl += '&pc=1'
        baseUrl += '&otf=1'
        baseUrl += '&ssel=3'
        baseUrl += '&tsel=6'
        baseUrl += '&kc=1'
        baseUrl += '&tk=' + self.get_tk(text)
        baseUrl += '&q=' + text
        return baseUrl

    def set_similar(self,l):
        len_similar = len(l[5][0][2])
        all_similar = set()
        all_similar.add(l[0][0][0])
        for i in range(len_similar):
            all_similar.add(l[5][0][2][i][0])
        return all_similar


    def run(self,text):
        rest=[]
        all_chinese = set()
        all_chinese.add(text)
        try:
            englishs_response = session.get(self.c2e_url(text),headers = self.headers,proxies =self.proxies,timeout=2)
            englishs = self.set_similar(json.loads(englishs_response.text))
            for i in englishs:
                chinese_response = session.get(self.e2c_url(i),headers = self.headers,proxies =self.proxies,timeout=2)
                chineses = self.set_similar(json.loads(chinese_response.text))
                all_chinese.update(chineses)
        except:
            raise TimeoutError
        for i in all_chinese:
            rest.append(i)
        # print('google')
        # print(rest)
        return rest
# if __name__ == '__main__':
#     '''
#     *  调用示例
#     *  from 路径.get_googlle_chinese import Google
#     *  Google().run('在这里输入中文')
#     *  返回值
#     *  ['在这里输入中文', '在此输入中国', '这里输入中文', '这里输入中国']
#     '''
#     try:
#         text = input('中文：')
#         print(Google().run(text))
#     except IndexError:
#         print('shell运行示例: python google.py 在这里输入中文')
#     except TimeoutError as e:
#         print('爬的太猛了,被谷歌发现了')
#     except BaseException as e:
#         print('未知错误')
#         print(e)